package com.scut.miaosha.access;

import com.alibaba.fastjson.JSON;
import com.scut.miaosha.Result.CodeMsg;
import com.scut.miaosha.Result.Result;
import com.scut.miaosha.domain.MiaoshaUser;
import com.scut.miaosha.redis.AccessKey;
import com.scut.miaosha.redis.MiaoshaKey;
import com.scut.miaosha.redis.RedisService;
import com.scut.miaosha.service.MiaoshaService;
import com.scut.miaosha.service.MiaoshaUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;


//方法的拦截器
@Service
public class AccessInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    public MiaoshaService miaoshaService;

    @Autowired
    public RedisService redisService;

    @Autowired
    public MiaoshaUserService miaoshaUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if(handler instanceof HandlerMethod){
            MiaoshaUser user = getUser(request,response);
            UserContext.setUser(user);
            //方法
            HandlerMethod hm = (HandlerMethod) handler;
            //方法上的注解
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if(accessLimit == null){
                return true;
            }

            int seconds = accessLimit.seconds();
            int maxCount = accessLimit.maxCount();
            boolean needLogin = accessLimit.needLogin();

            //user_id + requestURL
            String key = request.getRequestURI();
            if(needLogin){
                if(user == null){
                     render(response , CodeMsg.SESSION_ERROR);
                    //表示不进这个页面了
                    return false;
                }
                key += "_" + user.getId();

            }else{
                //do nothing
            }
            //martion flower 重构改善弟代码设计
            AccessKey ak = AccessKey.withExpire(seconds);
            Integer count = redisService.get(ak,key,Integer.class);
            //第一次访问
            if(count == null){
                redisService.set(ak,key,1);
            }else if(count < maxCount){
                redisService.incr(ak,key);
            }else{
                render(response , CodeMsg.ACCESS_LIMIT_REACH);
                return false;
            }
        }

        return true;
    }

    private  void render(HttpServletResponse response,CodeMsg cm) throws Exception{
        response.setContentType("application/json;charset=UTF-8");
        OutputStream out = response.getOutputStream();
        String str =  JSON.toJSONString(Result.error(cm));
        out.write(str.getBytes("UTF-8"));
        out.flush();
        out.close();
    }

    private MiaoshaUser getUser(HttpServletRequest request, HttpServletResponse response){
        String paramToken = request.getParameter(MiaoshaUserService.COOKIE_NAME_TOKEN);
        String cookieToken = getCookieValue(request,MiaoshaUserService.COOKIE_NAME_TOKEN);
        if(StringUtils.isEmpty(cookieToken) && StringUtils.isEmpty(paramToken))
        {
            return null;
        }
        //优先取paramToken
        String token = StringUtils.isEmpty(paramToken)?cookieToken:paramToken;
        MiaoshaUser user = miaoshaUserService.getByToken(response , token);
        return user;
    }

    private String getCookieValue(HttpServletRequest request, String cookieName) {
        Cookie[] cookies = request.getCookies();
        if(cookies == null || cookies.length <= 0)
        {
            return null;
        }
        for(Cookie cookie : cookies)
        {
            if(cookie.getName().equals(cookieName))
            {
                return cookie.getValue();
            }
        }
        return null;
    }

}
